<template>
	<view class="page">
		<view style="padding-top: 26rpx">
			<view class="module">
				<view class="banner">
					<image :src="path + data.meetingImg"></image>
				</view>
				<view class="info">
					<view class="flex-b" style="margin-bottom: 20rpx">
						<!-- <view class="title">{{data.meetingName}}</view> -->
					<view class="room-title flex items-center">  
					  <!-- 左侧内容 --> 
					  <view class="mr-2">{{ data.meetingName }}</view>
					  <view class="price text-sm text-gray-500" style="margin-left: 30rpx;" v-if="!data.meetingTopic">需联系物业开门</view>
					  <!-- 右侧内容（新增 flex-shrink: 0 防止内容被压缩） -->
					  <view style="color: rgba(102, 102, 102, 1); margin-left: 80rpx;">
					    <view class="price" v-if="data.price">{{ data.price || '0' }}元/小时</view>
					    <view class="price text-sm text-gray-500" v-else>限时免费</view>
					  </view>
					</view>
						
						
					</view>
					<!-- <view class="text">
						已售
						<span class="num">1</span>
					</view> -->
					<view class="cz">
						<view class="adaress">{{data.meetingAddress || ''}}</view>
						<view class="flex">
							<!-- <image style="width: 64rpx; height: 64rpx; margin-right: 16rpx" src="/static/image/icon-1.png"></image>
							 -->
							<image @click="callPhone()" style="width: 64rpx; height: 64rpx"
								src="/static/image/icon-2.png"></image>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="module2">
			<view class="time-list">
				<view class="time-item" :class="wIndex===index?'newDate':''" v-for="(item,index) in dateList"
					:key="index" @click="clickDate(index)">
					<view class="f-24" style="margin-bottom: 10rpx">{{item.dayOfWeek}}</view>
					<view class="f-32" style="font-weight: 500">{{jx(item.date)}}</view>
				</view>
			</view>
			<!-- 添加小时选择 -->
			<!-- <view>
				<view class="form-item flex" style="margin-top: 20rpx">
					<view style="margin-right: 12rpx">选择时段</view>
					<view class="example-body">
						 <view class="tag-view" v-for="(item,index) in minHoursList">
							 <uni-tag :inverted="true" size="normal" :text="getMinHours(data.minHours,index)+'小时'" type="success" />
						</view> 
					</view>
				</view>
			</view> -->

			<view class="form">
				<picker mode="time" :start="startStartTime" :end="startEndTime" @change="changeLog">
					<view class="form-item flex">
						<view style="margin-right: 12rpx">开始时间</view>
						<input disabled v-model="startDate" placeholder="请选择开始" />
					</view>
				</picker>
				<picker mode="time" :start="endStartTime" :end="endEndTime" @change="changeLog2">
					<view class="form-item flex">
						<view style="margin-right: 12rpx">结束时间</view>
						<input disabled v-model="endDate" placeholder="请选择结束" />
					</view>
				</picker>
			</view>
			<time-slot :currentDay="currentDay" :minHours="data.minHours" :disTimeArr="disTimeArr"></time-slot>
		</view>
		<view class="module3">
			<view class="title-b">
				<view class="name">优惠券</view>
				<view class="text">
					无优惠券
					<image src="/assets/my/1.png" style="width: 14rpx; height: 24rpx"></image>
				</view>
			</view>
		</view>
		<view class="pf-bottom">
			<view class="">
				<view class="price" v-if="data.price">{{ data.price || '0' }}元/小时</view>
				<view class="price" v-else>限时免费</view>
				<view class="time">共{{numHours}}小时</view>
			</view>
			<view class="btn" @click="goUrl()">确定预约</view>
		</view>
	</view>
</template>
<script>
	import timeSlot from '@/components/time-slot/time-slot.vue';
	import {
		getTimeFrameByList,
		getPath
	} from '@/api/main/main';
	export default {
		components: {
			timeSlot
		},
		data() {
			return {
				wIndex: 0,
				path: getPath(),
				startStartTime: '08:00',
				startEndTime: '18:00',
				endStartTime: '08:00',
				endEndTime: '18:00',
				startDate: '',
				endDate: null,
				meetingId: '',
				data: {},
				dateList: [],
				disTimeArr: [],
				numHours: 0,
				currentDay: '',
				minHoursList: [1, 2, 3, 4]
			};
		},
		onLoad(o) {
			this.getFutureWeekDates()
			if (o.item) {
				this.data = JSON.parse(o.item)
				this.meetingId = this.data.id;
				this.getTimeByList();
			}
		},
		methods: {
			selectPackage(index) {
				this.selectedPackageIndex = index;
			},
			callPhone(val) {
				uni.makePhoneCall({
					phoneNumber: this.data.phone,
				})
			},
			clickDate(index) {
				this.wIndex = index
				this.currentDay = this.dateList[this.wIndex].date
				if (index != 0) {
					this.start = ''
				}
				console.log("index-->", index);
				// this.compareTimes(this.startDate, this.endDate)
				if (this.compareTimes(this.startDate, this.endDate)) {
					if (this.startDate && this.endDate) {
						this.numHours = this.calculateHoursDifference(this.startDate, this.endDate)
					}
				}
				this.getTimeByList()
			},
			getMinHours(val, index) {
				return val + (2 * index);
			},
			jx(val) {
				return val.substring(8, 10)
			},
			calculateHoursDifference(time1, time2) {
				const dateFormat = "HH:mm";
				const date1 = new Date(`${this.dateList[this.wIndex].date}T${time1}`);
				const date2 = new Date(`${this.dateList[this.wIndex].date}T${time2}`);
				const diffInMilliseconds = Math.abs(date2 - date1);
				const diffInHours = diffInMilliseconds / (1000 * 60 * 60);
				return diffInHours.toFixed(2);
			},
			//获取日期列表
			getFutureWeekDates() {
				const today = new Date();
				const dates = [];
				for (let i = 0; i < 7; i++) {
					const date = new Date(today);
					date.setDate(today.getDate() + i);
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					const formattedDate = `${year}-${month}-${day}`;
					const dayOfWeek = this.formatDateToTodayOrWeekday(formattedDate);
					dates.push({
						date: formattedDate,
						dayOfWeek: dayOfWeek
					});
				}
				this.dateList = dates;
				this.dateList.forEach(item => {
					if (item.date == this.data.startDate) {
						this.wIndex = this.dateList.indexOf(item)
					}
				})
				this.currentDay = this.dateList[this.wIndex].date
				console.log(this.dateList)
			},
			// 分析日期
			formatDateToTodayOrWeekday(inputDateString) {
				let now = new Date();
				let year = now.getFullYear();
				let month = now.getMonth() + 1; // 月份是从0开始的，所以需要+1
				let day = now.getDate();
				let dateString = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
				// this.start = now.getHours() + ':' + now.getMinutes()
				if (now.getHours() > 8) {
					this.startStartTime = now.getHours() + ':' + now.getMinutes()
				} else {
					this.startStartTime = '08:00'
				}

				if (inputDateString === dateString) {
					return "今天";
				} else {
					let weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
					let inputDate = new Date(inputDateString);
					let weekday = weekdays[inputDate.getDay()];
					return weekday;
				}
			},
			changeLog(e) {
				this.startDate = e.target.value;
				this.endStartTime = e.target.value;
				if (this.compareTimes(this.startDate, this.endDate)) {
					if (this.startDate && this.endDate) {
						this.numHours = this.calculateHoursDifference(this.startDate, this.endDate)
					}
				}
			},
			changeLog2(e) {
				this.endDate = e.target.value;
				if (this.compareTimes(this.startDate, this.endDate)) {
					if (this.startDate && this.endDate) {
						this.numHours = this.calculateHoursDifference(this.startDate, this.endDate)
					}
				}
			},
			compareTimes(startTime, endTime) {
				console.log("compareTimes : ", startTime, endTime);
				if (startTime && endTime) {
					// 将时分字符串转换为分钟数
					const toMinutes = (timeStr) => {
						const [hours, minutes] = timeStr.split(':').map(Number);
						return hours * 60 + minutes;
					};
					const startMinutes = toMinutes(startTime);
					const endMinutes = toMinutes(endTime);

					if (startMinutes < endMinutes) {
						return true
						// return "提示：开始时间早于结束时间";
					} else if (startMinutes > endMinutes) {
						return false
						// return "结束时间晚于开始时间";
					} else {
						return false
						// return "开始时间和结束时间相同";
					}
				}
			},
			goUrl() {
				if (!this.startDate) {
					uni.showToast({
						title: '请选择开始时间',
						icon: 'none'
					})
					return
				}
				if (!this.endDate) {
					uni.showToast({
						title: '请选择结束时间',
						icon: 'none'
					})
					return
				}
				console.log("this.numHours", this.numHours);
				if (this.numHours < this.data.minHours) {
					uni.showToast({
						title: '至少预约' + this.data.minHours + ' 小时起',
						icon: 'none'
					})
					return
				}
				this.compareTimes(this.startDate, this.endDate)
				let nyr = this.dateList[this.wIndex].date
				if (this.compareTimes(this.startDate, this.endDate)) {
					const isConflict = this.isOverlapping(this.disTimeArr, new Date(nyr + ' ' + this.startDate), new Date(
						nyr + ' ' + this.endDate));
					if (isConflict) {
						uni.showToast({
							title: '所选时间段与已有预定重叠',
							icon: 'none'
						})
						console.log("❌ 冲突：所选时间段与已有预定重叠。");
					} else {
						let item = {
							startDate: nyr + ' ' + this.startDate + ':00',
							endDate: nyr + ' ' + this.endDate + ':00',
							numHours: this.numHours,
							...this.data
						}
						uni.navigateTo({
							url: '/pages/order/pay?item=' + JSON.stringify(item)
						});
					}

				}

			},
			// 检查选中范围是否与任何已有范围重叠
			isOverlapping(existingRanges, selectedStart, selectedEnd) {
				for (const range of existingRanges) {
					const existingStart = new Date(range.startDate);
					const existingEnd = new Date(range.endDate);
					if (
						// 完全包含
						(selectedStart >= existingStart && selectedEnd <= existingEnd) ||
						// 部分重叠
						(selectedStart < existingEnd && selectedEnd > existingStart)
					) {
						return true;
					}
				}
				return false;
			},



			getTimeByList() {
				getTimeFrameByList({
					meetingId: this.meetingId, //会议室id
					date: this.dateList[this.wIndex].date //日期 yyyy-MM-dd
				}).then((res) => {
					if (res.data && res.data.length > 0) {
						res.data.forEach(item => {
							item.begin_time = item.startDate
							item.end_time = item.endDate
						})
						this.disTimeArr = res.data
					} else {
						this.disTimeArr = []
					}
					console.log("更新时间结束 ===== ", this.disTimeArr);
					//开始更新开始时间
					this.startDate = this.findAvailableStartTime(this.disTimeArr, this.data.minHours,this.dateList[this.wIndex].date);
					if (this.startDate == null) {
						uni.showToast({
							title: '选择时间已约满!',
							icon: 'none'
						})
						setTimeout(() => {
							this.wIndex = this.wIndex + 1;
							this.clickDate(this.wIndex);
						}, 1200)
						return;
					}
					this.startStartTime = this.startDate;
					console.log("更新开始时间=====", this.startDate);
					this.endStartTime = this.calculateEndTime(this.startDate, this.data.minHours);
					console.log("更新结束时间=====", this.endStartTime);
				});
			},
			/**
			 * 根据开始时间和最小预约时长计算结束时间
			 * @param {string} startTime - 开始时间（格式：HH:MM）
			 * @param {number} minHours - 最小预约小时数（支持小数，如 1.5 表示1小时30分钟）
			 * @returns {string} 结束时间（格式：HH:MM）
			 */
			calculateEndTime(startTime, minHours) {
				// 解析开始时间
				const [hoursStr, minutesStr] = startTime.split(':');
				const hours = parseInt(hoursStr, 10);
				const minutes = parseInt(minutesStr, 10);
				// 创建开始时间的 Date 对象（使用今天的日期）
				const startDate = new Date();
				startDate.setHours(hours, minutes, 0, 0);
				// 计算分钟数（将小时转换为分钟）
				const totalMinutes = minHours * 60;
				// 创建结束时间的 Date 对象
				const endDate = new Date(startDate.getTime() + totalMinutes * 60 * 1000);
				// 格式化为 HH:MM
				const endHours = String(endDate.getHours()).padStart(2, '0');
				const endMinutes = String(endDate.getMinutes()).padStart(2, '0');
				return `${endHours}:${endMinutes}`;
			},
			/**
			 * 查找会议室可用预约时段（返回当天符合条件的第一个开始时间，格式为 HH:MM）
			 * @param {Array} bookedSlots - 已预约时段列表，每个元素包含 begin_time 和 end_time 字符串
			 * @param {number} minBookingHours - 最小预约小时数
			 * @returns {string|null} 可用的开始时间（格式：HH:MM），若无符合条件的时段则返回 null
			 */
			findAvailableStartTime(bookedSlots, minBookingHours,targetDate) {
				console.log("findAvailableStartTime 入参", bookedSlots, minBookingHours,targetDate);
				 // 辅助函数：解析时间字符串为 Date 对象
				  function parseDateTime(dateTimeStr) {
				    if (dateTimeStr.endsWith('24:00:00')) {
				      dateTimeStr = dateTimeStr.replace('24:00:00', '00:00:00');
				      const nextDay = new Date(dateTimeStr);
				      nextDay.setDate(nextDay.getDate() + 1);
				      return nextDay;
				    }
				    return new Date(dateTimeStr.replace(' ', 'T'));
				  }
				
				  // 辅助函数：计算两个时间点之间的时间差（小时）
				  function getHoursDifference(start, end) {
				    return (end - start) / (1000 * 60 * 60);
				  }
				
				  // 辅助函数：格式化为 HH:MM
				  function formatTime(date) {
				    const hours = String(date.getHours()).padStart(2, '0');
				    const minutes = String(date.getMinutes()).padStart(2, '0');
				    return `${hours}:${minutes}`;
				  }
				
				  // 将目标日期转换为 Date 对象
				  const targetDay = new Date(targetDate);
				  const dayStart = new Date(targetDay);
				  dayStart.setHours(0, 0, 0, 0);
				  const dayEnd = new Date(targetDay);
				  dayEnd.setHours(23, 59, 59, 999);
				
				  // 过滤并排序目标日期的已预约时段
				  const targetBookedSlots = bookedSlots
				    .map(slot => ({
				      start: parseDateTime(slot.begin_time),
				      end: parseDateTime(slot.end_time)
				    }))
				    .filter(slot => slot.start >= dayStart && slot.start <= dayEnd)
				    .sort((a, b) => a.start - b.start);
				
				  // 如果没有已预约时段，返回当天开始时间
				  if (targetBookedSlots.length === 0) {
				    return formatTime(dayStart);
				  }
				
				  // 合并重叠的已预约时段
				  const mergedBookedSlots = [];
				  for (const slot of targetBookedSlots) {
				    if (mergedBookedSlots.length === 0) {
				      mergedBookedSlots.push(slot);
				      continue;
				    }
				    
				    const lastSlot = mergedBookedSlots[mergedBookedSlots.length - 1];
				    if (slot.start <= lastSlot.end) {
				      lastSlot.end = slot.end > lastSlot.end ? slot.end : lastSlot.end;
				    } else {
				      mergedBookedSlots.push(slot);
				    }
				  }
				
				  // 生成可用时间段
				  const availableSlots = [];
				  
				  // 第一个可用时段：从当天开始到第一个预约开始
				  if (mergedBookedSlots[0].start > dayStart) {
				    availableSlots.push({ start: dayStart, end: mergedBookedSlots[0].start });
				  }
				  
				  // 中间的可用时段：预约之间的间隙
				  for (let i = 0; i < mergedBookedSlots.length - 1; i++) {
				    const gapStart = mergedBookedSlots[i].end;
				    const gapEnd = mergedBookedSlots[i + 1].start;
				    if (gapStart < gapEnd) {
				      availableSlots.push({ start: gapStart, end: gapEnd });
				    }
				  }
				  
				  // 最后一个可用时段：最后一个预约结束到当天结束
				  const lastBookedSlot = mergedBookedSlots[mergedBookedSlots.length - 1];
				  if (lastBookedSlot.end < dayEnd) {
				    availableSlots.push({ start: lastBookedSlot.end, end: dayEnd });
				  }
				
				  // 查找第一个符合条件的可用时段
				  for (const slot of availableSlots) {
				    // 计算可用时长
				    const duration = getHoursDifference(slot.start, slot.end);
				    
				    // 如果可用时长大于等于最小预约时长，返回开始时间
				    if (duration >= minBookingHours) {
				      return formatTime(slot.start);
				    }
				  }
				
				  // 若无符合条件的时段，返回 null
				  return null;
			}
		}
	};
</script>

<style>
	.room-title {
		font-size: 34rpx;
		font-weight: 600;
		margin-bottom: 20rpx;
		color: #333;
		line-height: 1.4;
	} 
	
	
	.page {
		background: rgba(245, 245, 245, 1);
		height: 100vh;
	}

	input {
		width: 510rpx;
		height: 72rpx;
		line-height: 72rpx;
		border-radius: 8rpx;
		padding: 0 12rpx;
		background: rgba(243, 243, 243, 1);
	}

	.newDate {
		background: rgba(100, 194, 149, 1) !important;
		border-radius: 8rpx;
		color: #fff !important;
	}

	.f-24 {
		font-size: 24rpx;
	}

	.f-32 {
		font-size: 32rpx;
	}

	.num {
		color: rgba(100, 194, 149, 1);
	}

	.price {
		font-size: 28rpx;
		color: #FF6B6B;
		font-weight: 600;
	}

	.title {
		font-weight: 500;
		font-size: 32rpx;
		color: rgba(34, 34, 34, 1);
	}

	.module {
		background: #fff;
		border-radius: 16rpx;
		margin: 0 30rpx;
	}

	.banner image {
		width: 100%;
		height: 340rpx;
		border-radius: 16rpx;
	}

	.info {
		padding: 24rpx 24rpx 50rpx 24rpx;
	}

	.f0 {
		color: rgba(216, 31, 37, 1);
	}

	.flex-b {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.flex {
		display: flex;
		align-items: center;
	}

	.cz {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.pf-bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: #fff;
		padding: 8rpx 30rpx 42rpx;
	}

	.pf-bottom .btn {
		background: rgba(100, 194, 149, 1);
		border-radius: 50rpx;
		width: 236rpx;
		text-align: center;
		height: 84rpx;
		line-height: 84rpx;
		color: #fff;
	}

	.module2 {
		background: rgba(255, 255, 255, 1);
		border-radius: 16rpx;
		margin-top: 24rpx;
		background: #fff;
		padding: 14rpx 14rpx 32rpx;
		margin: 24rpx 30rpx;
	}

	.time-list {
		display: flex;
		align-items: center;
	}

	.time-item {
		background: rgba(243, 243, 243, 1);
		border-radius: 8rpx;
		margin-right: 10rpx;
		width: 86rpx;
		text-align: center;
		height: 130rpx;
		padding-top: 16rpx;
	}

	.time-item:last-child {
		margin-right: 0;
	}

	.form {
		margin-top: 40rpx;
		margin-bottom: 40rpx;
	}

	.form-item {
		margin-bottom: 24rpx;
	}

	.module3 {
		background: rgba(255, 255, 255, 1);
		border-radius: 16rpx;
		margin: 0 30rpx;
		padding: 24rpx;
	}

	.title-b {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.title-b .name {
		color: rgba(34, 34, 34, 1);
		font-size: 28rpx;
		font-weight: 500;
	}

	.title-b .text {
		font-size: 26rpx;
		color: rgba(153, 153, 153, 1);
	}

	.example-body {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		justify-content: flex-start;
		align-items: flex-end;
		flex-wrap: wrap;
	}

	.tag-view {
		margin-right: 30rpx;
	}
</style>